package com.itheima.reggie.controller.user;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.itheima.reggie.common.R;
import com.itheima.reggie.common.UserHolder;
import com.itheima.reggie.entity.ShoppingCart;
import com.itheima.reggie.service.ShoppingCartService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/shoppingCart")
public class ShoppingController {
    @Autowired
    ShoppingCartService shoppingCartService;

//    @PostMapping("/add")
    public R addShoppingCart_(@RequestBody ShoppingCart shoppingCart,
                             HttpSession session){

        // 获取用户id，设置用户id
        // Long userId = BaseContext.getCurrentId();
        Long userId = (Long) session.getAttribute("user");
    /* 菜品或者套餐是否点过
     如何知道烧鹅被点过了？？ 根据烧鹅的菜品id，查询下数据库中有没有烧鹅这个数据
     如何是菜品：select * from shopping_cart where dish_id = ? and user_id = ?
     如果是套餐：select * from shopping_cart where setmeal_id = ? and user_id = ?
     */
        LambdaUpdateWrapper<ShoppingCart> qw = new LambdaUpdateWrapper<>();
        qw.eq(ShoppingCart::getUserId,userId);
        // 判断当前用户点的是菜品还是套餐
        Long dishId = shoppingCart.getDishId();
        if(dishId!=null){//说明点的是菜品
            qw.eq(ShoppingCart::getDishId,dishId);
        }else {//如果不是菜品，那么一定是套餐
            qw.eq(ShoppingCart::getSetmealId,shoppingCart.getSetmealId());
        }
        ShoppingCart one = shoppingCartService.getOne(qw);
        // 第一次点的时候是新增 ，后面在点击的时候是修改
        if(one == null){
            // 如果没有，则是新增
            // 设置 number=1
            shoppingCart.setNumber(1);
            shoppingCart.setUserId(userId);
            shoppingCartService.save(shoppingCart);
        }else {
            // 如果有，则是更新
            one.setNumber(one.getNumber()+1);
            shoppingCartService.updateById(one);
        }

        return R.success("添加购物车成功！");
    }
    @PostMapping("/add")
    public R addShoppingCart(@RequestBody ShoppingCart shoppingCart, HttpSession session){
        Long userId = UserHolder.getUser().getId();
//        Long userId = (Long) session.getAttribute("user");
        log.info("用户id为：{}",userId.toString());
        LambdaQueryWrapper<ShoppingCart> lqw = new LambdaQueryWrapper<>();
        //特定用户的特定菜品/套餐之前存在就加一
        lqw.eq(ShoppingCart::getUserId,userId);
        Long dishId = shoppingCart.getDishId();
        Long setmealId = shoppingCart.getSetmealId();
        lqw.eq(dishId!=null, ShoppingCart::getDishId,dishId);
        lqw.eq(setmealId!=null,ShoppingCart::getSetmealId,setmealId);
        ShoppingCart one = shoppingCartService.getOne(lqw);
        if(one!=null){
            log.info(one.getNumber().toString());
            one.setNumber(one.getNumber()+1);
            one.setCreateTime(LocalDateTime.now());
            boolean update = shoppingCartService.update(one,lqw);
            return update?R.success("添加成功！！"):R.error("添加失败！！");
        }else{
        shoppingCart.setUserId(userId);
        shoppingCart.setNumber(1);
        shoppingCart.setCreateTime(LocalDateTime.now());
        }
        boolean update = shoppingCartService.save(shoppingCart);
        return update?R.success("添加成功！！"):R.error("添加失败！！");
    }

    @GetMapping("/list")
    public R selectShoppingCart(){
        LambdaQueryWrapper<ShoppingCart> lqw = new LambdaQueryWrapper<>();
        lqw.eq(ShoppingCart::getUserId, UserHolder.getUser().getId());
        lqw.orderByAsc(ShoppingCart::getCreateTime);
        List<ShoppingCart> list = shoppingCartService.list(lqw);
        return list!=null?R.success(list):R.error("查询失败！");
    }

//    @PostMapping("/sub")
    public R subShoppingCart_(@RequestBody ShoppingCart shoppingCart){
        //菜品或者套餐id 查询出当前ShoppingCart数据
        // 如何是菜品：select * from shopping_cart where dish_id = ? and user_id = ?
        // 如果是套餐：select * from shopping_cart where setmeal_id = ? and user_id = ?
        LambdaQueryWrapper<ShoppingCart> qw = new LambdaQueryWrapper<>();
        Long userId = UserHolder.getUserId();
        qw.eq(ShoppingCart::getUserId,userId);//where user_id =?
        Long dishId = shoppingCart.getDishId();
        if(dishId!=null){//是菜品
            qw.eq(ShoppingCart::getDishId,dishId);// dish_id = ?
        }else {// 是套餐
            qw.eq(ShoppingCart::getSetmealId,shoppingCart.getSetmealId());// setmeal_id = ?
        }
        ShoppingCart one = shoppingCartService.getOne(qw);
        // number -1 然后操作：
        Integer number = one.getNumber();
        number--;
        one.setNumber(number);
        if(number>0){
            // >0  update更新 update set number=? where id = ?
            shoppingCartService.updateById(one);
        }else {
            // <= 0  如何操作？ delete from shopping_cart where dish_id=? and user_id = ?
            shoppingCartService.remove(qw);
        }
        return R.success(one);
    }
    @PostMapping("/sub")
    public R subShoppingCart(@RequestBody ShoppingCart shoppingCart){
        LambdaQueryWrapper<ShoppingCart> lqw = new LambdaQueryWrapper<>();
        lqw.eq(ShoppingCart::getUserId,UserHolder.getUser().getId());
        Long dishId = shoppingCart.getDishId();
        Long setmealId = shoppingCart.getSetmealId();
        lqw.eq(dishId!=null, ShoppingCart::getDishId,dishId);
        lqw.eq(setmealId!=null,ShoppingCart::getSetmealId,setmealId);
        ShoppingCart one = shoppingCartService.getOne(lqw);
        boolean update=true;
        if(one.getNumber()>0){
            one.setNumber(one.getNumber()-1);
            one.setCreateTime(LocalDateTime.now());
            update = shoppingCartService.update(one,lqw);
        }
            return update?R.success("修改成功！！"):R.error("修改失败！！");
    }
    @DeleteMapping("/clean")
    public R cleanShoppingCart(){
        LambdaQueryWrapper<ShoppingCart> lqw = new LambdaQueryWrapper<>();
        lqw.eq(ShoppingCart::getUserId,UserHolder.getUser().getId());
        boolean remove = shoppingCartService.remove(lqw);
        return remove?R.success("成功！！"):R.error("失败！！");
    }
}
